import java.util.Comparator;
import java.util.PriorityQueue;

public class Test9 {
    public static int topK(int[] a, int k) throws Exception {
        if (k > a.length) {
            throw new Exception("k值有误");
        }
        //创建一个容量为k的最大堆
        PriorityQueue<Integer> integers = new PriorityQueue<>(k, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2 - o1;
            }
        });
        //先加入k个元素
        int i = 0;
        while (k != 0) {
            integers.offer(a[i]);
            i++;
            k--;
        }
        for (; i < a.length; i++) {
            if(a[i] < integers.peek()){
                integers.poll();
                integers.offer(a[i]);
            }
        }
        //返回堆顶元素
        return integers.peek();
    }

    public static void main(String[] args) throws Exception {
        int[] a = {3,4,5,1,2,8};
        int res = topK(a,5);
        System.out.println(res);
    }
}
